import router from "@/router";
import axios from "axios";
import { ElMessage } from "element-plus";
import { useTokenStore } from "@/stores/token";


//返回的是Axios的实例
const service = axios.create({
  baseURL: 'http://localhost:8080'
});

//Axios的请求拦截器
service.interceptors.request.use(function (config) {
  const tokenStore = useTokenStore();
  if (!config.url.startsWith("/login")) {
    // config.headers.token = sessionStorage.getItem('token');
    config.headers.token = tokenStore.tokenStr;
  }
  return config;
}, function (error) {
  return Promise.reject(error);
});

//Axios的响应拦截器
service.interceptors.response.use(resp => {
  
    // 获取续期的jwt
 let token = resp.headers.token;
 const tokenStore = useTokenStore();
 

 // 将续期的jwt放在store中
 if (token) {
  tokenStore.update(token);
  //  sessionStorage.setItem("token", token); // 确保新的 token 被存储
 }
    return resp.data;
}, error => {
  if (error.status == 403) {
    ElMessage.error({
      message: '令牌错误,请重新登录',
      duration: 1200,
      onClose: () => {
        sessionStorage.removeItem('token');
        router.push('/login');
      }
    })
  }
});

export default service;